from flask import Blueprint, url_for, render_template, request, current_app,redirect, abort, flash
from app import db
from app.utils.common import login_required
from app.models import Link
from app.constants import PAGE_LIMIT
from app.forms import LinkForm
from datetime import datetime

link_controller = Blueprint("link", __name__)

@link_controller.route("/link/index")
@login_required
def link():
    page = request.args.get("page", 1, type=int)
    try:
        pagination = Link.query.order_by(Link.id.desc()).paginate(page, per_page=PAGE_LIMIT)
    except Exception as e:
        current_app.logger.error(e)
        flash("获取链接失败")

    return render_template('admin/link/index.html', pagination=pagination)

@link_controller.route("/link/add", methods=['GET', 'POST'])
@login_required
def add_link():
    form = LinkForm()
    if request.method == "POST":
        if form.validate_on_submit():
            linkname = form.data.get('linkname')
            url = form.data.get('url')
            description = form.data.get('description')
            sort = form.data.get('sort')
            try:
                link = Link(linkname=linkname, url=url, description=description, sort=sort)
                db.session.add(link)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("添加链接失败")
            return redirect(url_for('link.link'))
        
    return render_template("admin/link/add.html", form=form)

@link_controller.route("/link/edit", methods=['GET', 'POST'])
@login_required
def edit_link():
    id = request.args.get("id", 0)
    try:
        link = Link.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("链接不存在")
        return redirect(url_for('link.link'))

    form = LinkForm(description=link.description, sort=link.sort)
    if request.method == "POST":
        if form.validate_on_submit():
            linkname = form.data.get('linkname')
            url = form.data.get('url')
            description = form.data.get('description')
            sort = form.data.get('sort')

            link.linkname = linkname
            link.url = url
            link.description = description
            link.sort = sort
            link.update_time = datetime.now()

            try:
                db.session.add(link)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("编辑链接失败")
            return redirect(url_for('link.link'))
        
    return render_template("admin/link/edit.html", form=form, link=link)

@link_controller.route("/link/delete", methods=['GET'])
@login_required
def del_link():
    id = request.args.get("id", 0, type=int)

    try:
        link = Link.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("链接不存在")
        return redirect(url_for('link.link'))
    
    if link:
        try:
            db.session.delete(link)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            flash("删除链接失败")

    return redirect(url_for('link.link'))